<!--  -->
<template>
  <div class="float-left">
    <div class="float-left j-b-flex mb-30">
      <div class="d-flex">
        <el-button type="danger" @click="delRecords()">删除</el-button>
      </div>
      <div class="d-flex">
        <div>
          <el-select
            v-model="filter.is_watched"
            class="w-150px"
            placeholder="看完"
          >
            <el-option
              v-for="(item, index) in statusMapRows"
              :key="index"
              :label="item.name"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </div>
        <div class="ml-10">
          <el-date-picker
            :picker-options="pickerOptions"
            v-model="watched_at"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="看完时间-开始"
            end-placeholder="看完时间-结束"
          >
          </el-date-picker>
        </div>

        <div class="ml-10">
          <el-button @click="paginationReset">清空</el-button>
          <el-button @click="firstPageLoad" type="primary">筛选</el-button>
          <el-button @click="importexcel" type="primary">导出表格</el-button>
        </div>
      </div>
    </div>
    <div class="float-left">
      <div class="float-left">
        <el-table
          :header-cell-style="{ background: '#f1f2f9' }"
          :data="records"
          class="float-left"
          @sort-change="sortChange"
          :default-sort="{ prop: 'id', order: 'descending' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="id" sortable label="ID" width="120">
          </el-table-column>
          <el-table-column label="学员">
            <template slot-scope="scope">
              <div class="user-item d-flex" v-if="users[scope.row.user_id]">
                <div class="avatar">
                  <img
                    :src="users[scope.row.user_id].avatar"
                    width="40"
                    height="40"
                  />
                </div>
                <div class="ml-10">
                  {{ users[scope.row.user_id].nick_name }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            property="progress"
            label="观看进度"
            sortable
            width="150"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.progress }}%</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="开始时间" width="240">
            <template slot-scope="scope">{{
              scope.row.created_at | dateFormat
            }}</template>
          </el-table-column>
          <el-table-column sortable label="看完时间" width="240">
            <template slot-scope="scope">{{
              scope.row.watched_at | dateFormat
            }}</template>
          </el-table-column>
          <el-table-column label="看完" width="80">
            <template slot-scope="scope">
              <span class="c-red" v-if="scope.row.is_watched === 1">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="float-left mt-30 text-center">
        <el-pagination
          @size-change="paginationSizeChange"
          @current-change="paginationPageChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import moment from "moment";
import XLSX from "xlsx";
export default {
  props: ["id"],
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      course_id: this.id,
      pagination: {
        page: 1,
        size: 10,
        sort: "id",
        order: "desc",
      },
      filter: {
        user_id: null,
        is_watched: null,
        watched_start_at: null,
        watched_end_at: null,
      },
      watched_at: [],
      total: 0,
      records: [],
      users: [],
      selectedRows: [],
      statusMapRows: [
        {
          name: "未看完",
          key: 0,
        },
        {
          name: "已看完",
          key: 1,
        },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    watched_at(newVal) {
      if (newVal) {
        this.filter.watched_start_at = newVal[0];
        this.filter.watched_end_at = newVal[1];
      } else {
        this.filter.watched_start_at = null;
        this.filter.watched_end_at = null;
      }
    },
  },
  //方法集合
  methods: {
    paginationReset() {
      this.watched_at = null;
      this.pagination.page = 1;
      this.filter.user_id = null;
      this.filter.is_watched = null;
      this.filter.watched_start_at = null;
      this.filter.watched_end_at = null;
      this.getRecords();
    },
    paginationSizeChange(size) {
      this.pagination.size = size;
      this.getRecords();
    },
    paginationPageChange(page) {
      this.pagination.page = page;
      this.getRecords();
    },
    firstPageLoad() {
      this.pagination.page = 1;
      this.getRecords();
    },
    sortChange(column) {
      this.pagination.sort = column.prop;
      this.pagination.order = column.order === "ascending" ? "asc" : "desc";
      this.getRecords();
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows;
    },
    getRecords() {
      let params = {};
      Object.assign(params, this.filter);
      Object.assign(params, this.pagination);
      if (params.is_watched === null) {
        params.is_watched = -1;
      }
      this.$request
        .get(`course/${this.course_id}/watch/records`, { params: params })
        .then((res) => {
          this.records = res.data.data.data;
          this.total = res.data.data.total;
          this.users = res.data.users;
        });
    },
    importexcel() {
      let params = {
        page: 1,
        size: this.total,
        sort: "id",
        order: "desc",
      };
      Object.assign(params, this.filter);
      if (params.is_watched === null) {
        params.is_watched = -1;
      }
      this.$request
        .get(`course/${this.course_id}/watch/records`, { params: params })
        .then((res) => {
          if (res.data.data.total === 0) {
            this.$message.error("数据为空");
            return;
          }

          let users = res.data.data.data;
          let print_data = [];
          let filename = `课程学习记录-${moment(new Date()).format(
            "YYYY-MM-DD HH:mm:ss"
          )}.xlsx`;
          for (let i in users) {
            print_data.push({
              用户id: users[i]?.id,
              用户: res.data.users[users[i]?.user_id].nick_name,
              手机号: res.data.users[users[i]?.user_id].mobile,
              观看进度: users[i]?.progress / 100 + "%",
              开始时间: moment(users[i]?.created_at).format("YYYY-MM-DD HH:mm"),
              结束时间:
                users[i]?.watched_at == null
                  ? ""
                  : moment(users[i]?.watched_at).format("YYYY-MM-DD HH:mm"),
            });
          }
          const new_sheet = XLSX.utils.json_to_sheet(print_data);
          const new_book = XLSX.utils.book_new();
          new_sheet["!cols"] = [
            { wch: 10 },
            { wch: 20 },
            { wch: 20 },
            { wch: 10 },
            { wch: 30 },
            { wch: 30 },
          ];
          XLSX.utils.book_append_sheet(new_book, new_sheet);
          XLSX.writeFile(new_book, filename);
        });
    },
    delRecords() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择需要操作的数据");
        return;
      }
      let ids = [];
      this.selectedRows.forEach((item) => {
        ids.push(item.id);
      });
      this.$request
        .post(`course/${this.course_id}/watch/records/delete`, {
          record_ids: ids,
        })
        .then(() => {
          this.$message.success(this.$t("common.success"));
          this.getRecords();
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.course_id = this.id;
    this.getRecords();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='less' scoped>
</style>